iT邦幫忙

0

visual studio dll lib 建立與呼叫

  • 分享至 

  • xImage
  •  

建立dll專案
https://i.imgur.com/Vr6frEt.png

新增檔案
https://i.imgur.com/8dzOeuN.png

設定不使用先行標題檔
https://i.imgur.com/ymIElaE.png

dllLib.h

#ifdef dll_EXPORTS
#define dll_API __declspec(dllexport)
#else
#define dll_API __declspec(dllimport)
#endif
extern “C”
{
    dll_API int dll_Init();
    dll_API int dll_Run(unsigned char *ucPara1, int dPara2);
    dll_API int dll_DeInit();
}

extern C將匯出 C 函式以用於 C 或 C++ 語言可執行檔
建置dll檔
https://i.imgur.com/a1itMQZ.png

建立空白專案來呼叫dll
https://i.imgur.com/XFxZxwN.png

新增檔案
https://i.imgur.com/qeSYer7.png

def function pointer

typedef int(*dll_Init_def)();
dll_Init_def dll_Init_p = NULL;
typedef int(*dll_Run_def)(unsigned char*, int);
dll_Run_def dll_Run_p = NULL;
typedef int(*dll_DeInit_def)();
dll_DeInit_def dll_DeInit_p = NULL;

宣告dll handle

HINSTANCE hdll = NULL;

loadLibrary

hdll = LoadLibrary(L"DllLib.dll");
if (hdll)
{
 // Bind functions
 dll_Init_p = (dll_Init_def)GetProcAddress(hdll, "dll_Init");
 dll_Run_p = (dll_Run_def)GetProcAddress(hdll, "dll_Run");
 dll_DeInit_p = (dll_DeInit_def)GetProcAddress(hdll, "dll_DeInit");
if (dll_Init_p == NULL ||
  dll_Run_p == NULL ||
  dll_DeInit_p == NULL)
 {
  printf("can not load func addr!!!\n");
  FreeLibrary(hdll);
  return 1;
 }
return 0;
}

也要記得close lib

if (hdll) FreeLibrary(hdll);

呼叫lib

dll_Init_p();
unsigned char* buf = (unsigned char*)malloc(sizeof(unsigned char) * 10);
strcpy((char*)buf, “dllCall”);
dll_Run_p(buf, 10);
dll_DeInit_p();

右鍵屬性選擇起始專案為exe
https://i.imgur.com/D3FhWvX.png

執行後即可呼叫
reference - https://docs.microsoft.com/zh-tw/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=msvc-170
github - https://github.com/bionicqq519/DllLib


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言